import { Injectable, NestMiddleware, UnauthorizedException } from '@nestjs/common';
import config from 'src/config/config';
import * as jwt from 'jsonwebtoken';
import { UserService } from 'src/service/user/user.service';

@Injectable()
export class ShopauthMiddleware implements NestMiddleware {
    constructor(private readonly userService: UserService) {}
    async use(req: any, res: any, next: () => void) {
        const whiteList = [
            { url: '/shop/user', method: 'get' },
            { url: '/shop/buy/aliPayNotify', method: 'post' },
        ];
        if (whiteList.some((item) => item.url === req.baseUrl && item.method.toLowerCase() === req.method.toLowerCase())) {
            next();
        } else {
            const authCookie = req.signedCookies[config.authCookieKey];
            if (!authCookie) throw new UnauthorizedException('请先登录');
            const { _id } = jwt.verify(authCookie, config.jwtSecret) as any;
            if (!_id) throw new UnauthorizedException('用户_id错误');
            const user = await this.userService.find({ _id });
            if (!user.length) throw new UnauthorizedException('用户不存在');
            next();
        }
    }
}
